package com.qf.fc.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.qf.fc.utils.JwtUtils;
import com.qf.fc.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0
 * @Author zhangH
 * @Date 2024/12/19 16:27
 */
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 从 Authorization 头中获取 Token
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            log.error("Authorization 头为空或格式错误");
            sendErrorResponse(response, "未登录");
            return false;
        }

        // 提取 Token
        String jwt = authHeader.substring(7);
        log.info("解析到的 Token: {}", jwt);

        // 验证 Token
        try {
            JwtUtils.parseJwt(jwt);
            log.info("令牌合法，放行");
            return true;
        } catch (Exception e) {
            log.error("Token 解析失败", e);
            sendErrorResponse(response, "未登录");
            return false;
        }
    }

    /**
     * 发送错误响应
     * @param response HttpServletResponse 对象
     * @param message 错误信息
     * @throws IOException 写入响应时可能抛出的异常
     */
    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        R result = R.fail(message);
        response.getWriter().write(JSONObject.toJSONString(result));
    }

    // controller层方法执行后，执行的方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    // 整个页面视图渲染完成后，执行的方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
